﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using RRD.Controller;
using RRD.DAL;
using System.Configuration;
using RRD.Model;

namespace RRD
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Scanner scanner;
        Logger logger;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            scanner = new Scanner();
            logger = new Logger();
            View();
            ViewFirstTimeRun();
        }
       
        private void Window_TextInput(object sender, TextCompositionEventArgs e)
        {
            string value = string.Empty;
            var message = new Message();
            try
            {
                if (e.Text.Contains('\r'))
                {
                    value = scanner.ReadBuffer();
                    message = scanner.CheckBarcode(value);
                    TextBlockMessage.Text = message.MessageValue;
                    this.Background = Visualiser.GetColorScan(message.MessageType); //zmienia kolor tła w zależności od typu komunikatu
                    ListBoxLogger.Items.Add(value);//zapisuje zeskanowane wartości do listbox'a
                    logger.WriteLog(value); //zapisuje zeskanowany kod do loga
                    scanner.ClearBuffer(); //czyści bufor odczytu
                    View();
                }
                else
                {
                    scanner.WriteBuffer(e.Text);
                }                
            }
            catch (Exception ex)
            {
                logger.WriteLog(ex.Message);
            }
        }

        private void View()
        {
            RectangleTruckStatus.Fill = scanner.GetTruckStatus();
            RectangleProdStatus.Fill = scanner.GetDBStatus(DatabaseType.Main);
            RectangleRFIDStatus.Fill = scanner.GetDBStatus(DatabaseType.RFID);
        }

        private void ViewFirstTimeRun()
        {
            TextBlockUserName.Text = Environment.UserName;
            TextBlockWorkstation.Text = Environment.MachineName;
            var title = ConfigurationManager.AppSettings["ApplicationName"].ToString();
            Version v = new Version();
            var version = string.Format("{0}.{1}.{2}",v.Major,v.Minor,v.Revision);
            this.Title = string.Format("{0} v.{1}",title,version);
        }
    }
}
